//
//  MCSignContractViewController.m
//  TLYL
//
//  Created by MC on 2017/11/3.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCSignContractViewController.h"
#import "MCContractMgtBaseModel.h"
#import "MCModifyOrSignContractTableViewCell.h"
#import "MCSignContractHeaderView.h"
#import "MCSignContractFooterView.h"
#import "MCGetDayWageActiveUserConditionModel.h"
#import "MCNaviSelectedPopView.h"
#import "MCInputView.h"

////////新制度
#import "MCMySubDaywagesNewModel.h"
#import "MCGetSubDaywagesNewModel.h"
#import "MCChangeSubDaywagesNewModel.h"
#import "MCDayWageGetSystemTypeModel.h"
@interface MCSignContractViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
typedef void(^MCSignContractVCCompeletion)(BOOL result, NSDictionary *data );

@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)ExceptionView * exceptionView;

@property(nonatomic, strong)MCSignContractHeaderView *headerView;
@property(nonatomic, strong)MCSignContractFooterView *footerView;

@property(nonatomic, strong)MCModifyOrSignContractTableViewCell *ex_cell;

//动态获取日结活跃人数条件
@property(nonatomic, strong)MCGetDayWageActiveUserConditionModel * getDayWageActiveUserConditionModel;
//获取自己和下级的日结契约
@property(nonatomic, strong)MCMySubDaywagesNewModel * mySubDaywagesNewModel;
//数据
@property(nonatomic, strong)MCMySubDaywagesNewDataModel * mySubDaywagesNewDataModel;
//添加修改日结
@property(nonatomic, strong)MCChangeSubDaywagesNewModel * changeSubDaywagesNewModel;


@property(nonatomic, strong)MCNaviSelectedPopView *popView1;
@property(nonatomic, weak)  MCInputView * viewPop1;
@property(nonatomic, assign) BOOL  isShowPopView1;
@property (nonatomic,strong) MCBaseGetSystemTypeModel * selected_SystemType;
@end

@implementation MCSignContractViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];

    [self setNav];

    [self createUI];

    [self refreashData];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [self dismissAllPopView1];
    
}


#pragma mark==================setProperty======================
-(void)setProperty{
    self.view.backgroundColor=RGB(231, 231, 231);
    if (_Type==MCSignOrModifyContractVCType_Modify) {
        self.navigationItem.title = @"更改契约";
    }else{
        self.navigationItem.title = @"签订契约";
    }
    self.selected_SystemType=self.SystemType;
}

#pragma mark ====================设置导航栏========================
-(void)setNav{
    
    UIButton *rightBtn = [[UIButton alloc] init];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"debss"] forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreashData];
    }];

    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(0);
        make.left.equalTo(self.view.mas_left).offset(13);
        make.right.equalTo(self.view.mas_right).offset(-13);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
}


#pragma mark-下拉刷新
- (void)refreashData{
    self.tableView.mj_footer.hidden=NO;

    [self.exceptionView dismiss];
    self.exceptionView = nil;

    [BKIndicationView showInView:self.view];
    __weak __typeof__ (self) wself = self;
    [self loadData:^(BOOL result, NSDictionary *data) {

        [wself.tableView.mj_footer endRefreshing];
        [wself.tableView.mj_header endRefreshing];

        if (result) {

            [wself setData:data];

        }else{

            wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                [wself.exceptionView dismiss];
                wself.exceptionView = nil;
                [wself refreashData];
            }];
            [wself.exceptionView addAction:action];
            [wself.exceptionView showInView:wself.view];
        }
    }];

    NSDictionary * dic = @{@"DayWagesTypeid":_SystemType.Id};
    MCGetDayWageActiveUserConditionModel * getDayWageActiveUserConditionModel = [[MCGetDayWageActiveUserConditionModel alloc]initWithDic:dic];
    [getDayWageActiveUserConditionModel refreashDataAndShow];
    self.getDayWageActiveUserConditionModel = getDayWageActiveUserConditionModel;
    
    getDayWageActiveUserConditionModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
    };
    
    getDayWageActiveUserConditionModel.callBackSuccessBlock = ^(id manager) {
        MCGetDaywagesActiveUserModel * getDaywagesActiveUserModel = [MCGetDaywagesActiveUserModel sharedMCGetDaywagesActiveUserModel];
        [getDaywagesActiveUserModel setTipWithData:manager];
        [wself.footerView refreashTip];
        
    };
}

#pragma mark==================loadData======================
-(void)loadData:(MCSignContractVCCompeletion)compeletion{
//    DwTypeId    是    Int    日结类型，从get_system_type中获取
//    SubUserId    是    Int    下级用户 ID
    NSDictionary * dic=@{
//                         @"UserID" : [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],
                         @"DwTypeId":_SystemType.Id,
                         @"SubUserId" : _xiaJiModel.UserID
                         };


    MCMySubDaywagesNewModel * mySubDaywagesNewModel = [[MCMySubDaywagesNewModel alloc]initWithDic:dic];
    [mySubDaywagesNewModel refreashDataAndShow];
    self.mySubDaywagesNewModel = mySubDaywagesNewModel;

    mySubDaywagesNewModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {

        compeletion(NO,nil);

    };

    mySubDaywagesNewModel.callBackSuccessBlock = ^(id manager) {

        compeletion(YES,manager);

    };

}

-(void)setData:(NSDictionary *)dic{

    _mySubDaywagesNewDataModel = [MCMySubDaywagesNewDataModel mj_objectWithKeyValues:dic];

    self.headerView.dataSource=_mySubDaywagesNewDataModel;
    
    self.headerView.xiaJiModel=_xiaJiModel;

    if ([[NSString stringWithFormat:@"%@",_mySubDaywagesNewDataModel.isAllowSign] isEqualToString:@"1"]) {
        self.footerView.contractBtn.hidden=NO;
    }else{
        self.footerView.contractBtn.hidden=YES;
    }
    
   
    [self.tableView reloadData];
}


#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return [MCSignContractHeaderView computeHeight:nil];
    }
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [MCSignContractFooterView computeHeight:nil];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    __weak __typeof__ (self) wself = self;
    
    self.footerView.block = ^{
        [wself setSignContract];
    };
    [self.footerView setFooterViewHidden:_mySubDaywagesNewDataModel];
    return self.footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return [MCModifyOrSignContractTableViewCell computeHeight:_mySubDaywagesNewDataModel];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *reuseIdentifier =[NSString stringWithFormat:@"MCModifyOrSignContractTableViewCell-%ld-%ld",(long)indexPath.section,(long)indexPath.row];

    MCModifyOrSignContractTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[MCModifyOrSignContractTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.dataSources=_mySubDaywagesNewDataModel;
    cell.mySubDaywagesNewDataModel=_mySubDaywagesNewDataModel;
    _ex_cell = cell;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-签订/修改日结契约
-(void)setSignContract{
    
  
    if (!_ex_cell.modifyOrSign_selectedModel) {
        [SVProgressHUD showInfoWithStatus:@"请选择日结标准！"];
        return;
    }
//    User_ID    是    Int    被修改人ID
//    subUserName （旧：UserName ）    是    String    被修改人姓名
//    ID    是    Int    新规则ID
//    DwTypeId    是    Int    日结类型ID
//    TypeName    是    String    日结类型名称
    
        __weak __typeof__ (self) wself = self;
        NSDictionary * dic=@{
                             @"subUserName" : _xiaJiModel.UserName,
                             @"User_ID" : _xiaJiModel.UserID,
                             @"ID"  : _ex_cell.modifyOrSign_selectedModel.ID,
                             @"DwTypeId":_SystemType.Id,
                             @"TypeName":_SystemType.Name
                                 
                             };
    NSString * Tip = @"";
    if (_Type == MCSignOrModifyContractVCType_Sign) {
        Tip=@"添加成功！";
    }else if (_Type == MCSignOrModifyContractVCType_Modify){
        Tip=@"修改成功！";
    }
    MCChangeSubDaywagesNewModel * changeSubDaywagesNewModel = [[MCChangeSubDaywagesNewModel alloc]initWithDic:dic];
    [changeSubDaywagesNewModel refreashDataAndShow];
    self.changeSubDaywagesNewModel = changeSubDaywagesNewModel;
    
    changeSubDaywagesNewModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        //                [SVProgressHUD showInfoWithStatus:@"签订失败！"];
    };
    
    changeSubDaywagesNewModel.callBackSuccessBlock = ^(id manager) {
        [SVProgressHUD showInfoWithStatus:Tip];
        [wself performSelector:@selector(delayMethod) withObject:nil afterDelay:2.0];
        wself.ex_cell.modifyOrSign_selectedModel=nil;
    };

}
-(void)delayMethod{
    if (self.goBackBlock) {
        self.goBackBlock();
    }
    [self refreashData];
}
#pragma mark-set/get
-(MCSignContractHeaderView *)headerView{
    if (!_headerView) {
        _headerView=[[MCSignContractHeaderView alloc]init];
    }
    return _headerView;
}

-(MCSignContractFooterView *)footerView{
    if (!_footerView) {
        _footerView=[[MCSignContractFooterView alloc]init];
    }
    return _footerView;
}
- (MCNaviSelectedPopView *)popView1{
    
    if (_popView1 == nil) {
        MCNaviSelectedPopView * popView1 = [[MCNaviSelectedPopView alloc]InitWithType:MCNaviSelectedPopType_addOrChangedayWageContract];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1)];
        [popView1 addGestureRecognizer:tap1];
        [self.navigationController.view addSubview:popView1];
        _popView1 = popView1;
    }
    return _popView1;
}
- (void)tap1{
    _isShowPopView1=NO;
    [self dismissAllPopView1];
}
-(void)dismissAllPopView1{
    [self.popView1 dismiss];
    [self.viewPop1 hiden];
}
- (MCInputView *)viewPop1{
    if (_viewPop1 == nil) {
        
        MCInputView *viewStatus = [[MCInputView alloc] init];
        [self.navigationController.view addSubview:viewStatus];
        _viewPop1 = viewStatus;
    }
    return _viewPop1;
}

-(void)rightBtnAction{
    
    if (_isShowPopView1) {
        _isShowPopView1=NO;
        [self.popView1 dismiss];
        
    }else{
        _isShowPopView1=YES;
        
        typeof(self) weakself = self;
        weakself.popView1.label1.text=weakself.SystemType.Name;
        self.popView1.block = ^(NSInteger type) {
            
            if (type==0) {
                weakself.popView1.label1.text=weakself.SystemType.Name;
                MCDayWageGetSystemTypeModel * dayWageGetSystemTypeModel = [MCDayWageGetSystemTypeModel sharedMCDayWageGetSystemTypeModel];
                
                NSArray * arr = dayWageGetSystemTypeModel.nameDataSource;
                NSArray * Marr =dayWageGetSystemTypeModel.dayWageDataSource;
                weakself.viewPop1.dataArray =  arr;
                [weakself.viewPop1 show];
                weakself.viewPop1.cellDidSelectedTop = ^(NSInteger i) {
                    
                    MCBaseGetSystemTypeModel * model =  Marr[i];
                    weakself.selected_SystemType=model;
                    weakself.popView1.label1.text=arr[i];
                    [weakself.viewPop1 hiden];
                    
                };
                
#pragma mark-搜索
            }else if (type==8){
                
                weakself.isShowPopView1=NO;
                [weakself dismissAllPopView1];
                if (weakself.selected_SystemType) {
                    weakself.SystemType=weakself.selected_SystemType;
                }
                [weakself refreashData];
            }
        };
        
        self.popView1.frame= CGRectMake(0, kStatusBarAndNavigationBarHeight, G_SCREENWIDTH, G_SCREENHEIGHT);
        [self.popView1 showPopView];
    }
}

@end




























